package com.example.asus_pc.myshop.activity;

import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.asus_pc.myshop.R;
import com.example.asus_pc.myshop.bean.User;

import java.util.ArrayList;
import java.util.List;

public class AddHotel extends AppCompatActivity {

    private int flag = 0;
    private ListView lv;//xml里的ListView
    private BaseAdapter adapter;//要实现的类
    private List<User> userList = new ArrayList<User>();//实体类
    private List<User> hotelList = new ArrayList<User>();
    private int num = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_hotel);
        lv = (ListView) findViewById(R.id.lv_name_price);

        final SharedPreferences userVeg = getSharedPreferences("Veg", 0);


        String[] Vegs = {"鸡蛋","白条鸡","韭菜","茴香","香菜","小葱","青椒","尖椒","黄瓜","西红柿","土豆","茄子","西湖",
        "长豆角","无丝豆","大扁","白葱头","红葱头","胡萝卜","白萝卜","大葱","大白菜","甘蓝","有机菜花",
                "西兰花","菜花","杭椒","金瓜","小绿瓜","苦瓜","丝瓜","姜","蒜苔","蒜苗","蒜黄","花生","毛豆",
                "红椒","娃娃菜","蒜米","水芹","香亭","豆苗","金针菇","白玉菇","杏鲍菇","香菇","根达菜","生菜",
                "油麦","油菜","圆生菜","小白菜","空心菜","苦菊","菠菜","豆芽","豆嘴","大蒜","藕","片粉","豆皮",
                "豆腐","豆腐丝","烧饼","拉皮（大）","拉皮","土豆粉","马粉","十八里（散）","十八里（1斤）",
                "王家粉条","玉米面","玉米茬","绿豆","香蕉","苹果","桃","葡萄","火龙果","橘子","橙子","西瓜",
                "梨","花卷","凉皮","面条","饼条","扁豆角","荷兰豆","绿白菜","紫甘蓝","线椒","米椒","美人椒","元丝瓜","小冬瓜","大冬瓜"

        };

        for (int i = 0; i < Vegs.length; i++) {
            User ue = new User();//给实体类赋值
            ue.setNum(String.valueOf(i+1));
            ue.setName(Vegs[i]);
            String price = userVeg.getString(Vegs[i],"1.0");
            ue.setPrice(price);
            ue.setChecked(false);
            userList.add(ue);
        }

        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                // TODO Auto-generated method stub
                return userList.size();//数目
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }


            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                LayoutInflater inflater = AddHotel.this.getLayoutInflater();
                final ViewHolder vh;
                if (convertView == null) {
                    if(flag == 0)
                    convertView = inflater.inflate(R.layout.item_hotel, null);
                    else if(flag == 1)
                        convertView = inflater.inflate(R.layout.item_hotel_bill, null);
                    vh = new ViewHolder(convertView);
                    convertView.setTag(vh);
                }else{
                    vh = (ViewHolder) convertView.getTag();
                }

                final User ue = userList.get(position);
                if(TextUtils.isEmpty(ue.getNum()) && (num-1 == position)) {
                    vh.tv1.setText(ue.getNum());
                    vh.tv2.setText(ue.getName());//设置参数
                    vh.tv3.setText(ue.getPrice());//设置参数
                    vh.tv4.setText("合计："+ue.getHotel_bill()+"元");
                }
                else {
                    vh.tv1.setText(ue.getNum());
                    vh.tv2.setText(ue.getName());//设置参数
                    vh.tv3.setText(ue.getPrice() + "元/斤");//设置参数
                    if(flag == 1)
                    {
                        vh.tv4.setText("订购"+ ue.getMass()+ "斤," + "总共"+ ue.getMassprice() + "元");
                    }
                }

                    //把User与输入框进行绑定
                vh.et.setTag(ue);

                //清除焦点
                vh.et.clearFocus();


                vh.et.addTextChangedListener(new TextWatcher() {
                    @Override
                    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                    }

                    @Override
                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        //获得Edittext所在position里面的Bean，并设置数据
                        User ue = (User)vh.et.getTag();
                        ue.setMass(s + "");
                        ue.setChecked(true);
                    }

                    @Override
                    public void afterTextChanged(Editable s) {

                    }
                });
                //大部分情况下，getview中有if必须有else
                if(!TextUtils.isEmpty(ue.getMass())){
                    vh.et.setText(ue.getMass());

                }else{
                    vh.et.setText("");
                }

                return convertView;
            }
             class ViewHolder{
                 TextView tv1;// Veg_num
                 TextView tv2;//item.xml里的TextView：Veg_name
                 TextView tv3;//item.xml里的TextView：Veg_price
                 TextView tv4;
                 EditText et;

                public ViewHolder(View view) {
                    tv1 = (TextView)view.findViewById(R.id.Veg_num);
                    tv2 = (TextView)view.findViewById(R.id.Veg_name);//找到Veg_name
                    tv3 = (TextView)view.findViewById(R.id.Veg_price);//找到Veg_name
                    tv4 = (TextView)view.findViewById(R.id.veg_bill);//veg_bill
                    et = (EditText) view.findViewById(R.id.et_mass);
                }
            }
        };
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:    //当停止滚动时
                        break;

                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:    //滚动时

                        //没错，下面这一坨就是隐藏软键盘的代码
                        ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(AddHotel.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                        break;

                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:   //手指抬起，但是屏幕还在滚动状态
                        break;
                }
            }

            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {

            }
        });
        lv.setAdapter(adapter);

    }
    public void add_hotel_button(View view) throws InterruptedException {
        hotelList.clear();
        User user;
        float mass;
        float massprice;
        float price;
        float hotel_bill = 0;
        flag = 1;
        num = 1;

        for(int i = 0; i < userList.size(); i++) {
            if (!TextUtils.isEmpty(userList.get(i).getMass())) {
                user = userList.get(i);

                mass = Float.parseFloat(user.getMass());
                price = Float.parseFloat(user.getPrice());

                massprice = mass * price;
                hotel_bill = hotel_bill + massprice;
                java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.0");
                String str = myformat.format(massprice);
                user.setMassprice(String.valueOf(str));
                user.setNum(String.valueOf(num));
                num++;
                hotelList.add(user);
            }
        }
        user = userList.get(num);
        user.setName("");
        user.setNum("");
        user.setPrice("");
        java.text.DecimalFormat myformat=new java.text.DecimalFormat("0.0");
        String str = myformat.format(hotel_bill);
        user.setHotel_bill(str);
        hotelList.add(user);
        userList.clear();
        userList = hotelList;
        lv.setAdapter(adapter);

    }
}
